package com.zzf.concurrent.example.design.pattern.two.phase.termination;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author GaoFeng2017
 * @date 2019/9/10 14:54
 */
@Slf4j
public class ClientSocketHandler implements Runnable {

    /** 客户端连接 */
    private Socket socket;

    /** 当前连接是否已停止 */
    private volatile boolean isStop;

    public ClientSocketHandler(Socket socket) {
        this.socket = socket;
        this.isStop = false;
    }

    @Override
    public void run() {
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter printWriter = new PrintWriter(outputStream)) {

            String message = null;

            // 阻塞读取
            while ((message = bufferedReader.readLine()) != null && !isStop) {
                log.info("receive message -> {}", message);
                printWriter.write("success receive data > " + message);
                printWriter.flush();
            }

        } catch(IOException e) {
            log.error("fail to read from client", e);
        } finally {
            log.info("client socket will be stop");
            stop();
        }
    }

    public void stop() {
        if (isStop) {
            return;
        }

        this.isStop = true;

        try {
            this.socket.close();
        } catch (IOException e) {
            log.error("fail to close client socket", e);
        }

        log.info("client socket is stopped.");
    }


}
